/**
 * Created by lixiaodi on 2019/05/06 0027.
 */
//模拟书结构数据

mini.parse();
//得到元素
var tree = mini.get('tree1');
var grid = mini.get('datagrid1');
var editWindow = mini.get("editWindow");
//按钮栏按钮
var addBtn = mini.get('addBtn');			//增加按钮
var editBtn = mini.get('editBtn');			//编辑按钮
var removeBtn = mini.get('removeBtn');		//删除按钮
//var releaseBtn = mini.get('releaseBtn');	//发布按钮
var editModelBtn = mini.get('editModel');			//编辑模型按钮
var removeModelBtn = mini.get('removeModel');		//删除模型按钮
var classNameEl = mini.getByName('modelClassName');	//得到分类名称填写框
//下拉按钮
var addModelBtn = mini.get('addModelBtn');
//初始化变量
var url = bootPATH + "../frame/frame1/pages/";      //路径前缀
var pid = '';										//父级id
var classState = true;								//新增:true;编辑false
var menu = new ColumnsMenu(grid);
//初始化
$(function(){
	//加载菜单树结构
	treeHttpRequest();
});
//右键菜单
function onBeforeOpen(e){
	//菜单(节点操作)
	var menu = e.sender;
	//得到被选择的节点
    var node = tree.getSelectedNode();
    if (!node) {
        e.cancel = true;
        return;
    }
    //按钮显示隐藏
    var editItem = mini.getbyName("edit", menu);
    var removeItem = mini.getbyName("remove", menu);
    editItem.show();
    removeItem.enable();

    if (node.id == "forms") {
        editItem.hide();
    }
    if (node.id == "lists") {
        removeItem.disable();
    }
}

//在节点之后插入(平级)
function onAddAfter(e) {
	classState = true;
    var tree = mini.get("tree1");
    var node = tree.getSelectedNode();
    //弹出
    editWindow.show();
    var form = new mini.Form("#editform");
    form.clear();
    //判断该节点有无父节点（有：得到父节点id；无：父节点id为-1）
    if(node._pid == -1){
    	//无父id
    	pid = -1;
    }else{
    	//有父id
    	pid = node.pid;
    }
}

//插入子节点
function onAddNode(e) {
	classState = true;
    var node = tree.getSelectedNode();
    //弹出
    editWindow.show();
    var form = new mini.Form("#editform");
    form.clear();
    //父节点赋值
    pid = node.id;
}

//编辑分类节点
function onEditNode() {
	classState = false;
    var node = tree.getSelectedNode();
    var nodeObj = {
    		id: node.id,
    		modelClassName: node.modelClassName
    }
    //tree.beginEdit(node);    
	 //弹出
    editWindow.show();
    var form = new mini.Form("#editform");
    form.setData(nodeObj);
}
//当编辑结束的时候
function onEndedit(e){
	
	var classId = e.node.id ? e.node.id : '';
	var className = e.text;
	classRequest(className,pid,classId);
}

//删除分类
function onRemoveNode(){
	var node = tree.getSelectedNode();
	if(node){
		mini.confirm('是否确定删除分类','系统提示',function(action){
			if(action == 'ok'){
				var nodeId = node.id;
				var idObj = {
						id: nodeId
				}
				var idString = JSON.stringify(idObj);
				// //加密
				// idString = encrypt(idString);
				$.ajax({
					 url: ajaxUrl + "/modelClass/deleteModelClass.do",
					 type:"post",
					 data: idString,
					 contentType : "application/utf-8",
					 success: function(data){
						 //解密
						 // var decryptData = decrypt(data);
						 decryptData = data;
						 if(decryptData.state == 'success'){
							 mini.alert(decryptData.message);
							 treeHttpRequest();
						 }else{
							 mini.alert(decryptData.message);
						 }
					 },
					 error: function(data){
						 
					 }
				})
			}
		})
		
	}else{
		mini.alert('请选择要删除的节点');
	}
}
//点击树节点的时候
tree.on("nodeselect", function (e) {
	//启用按钮
	addBtn.enable();
	editBtn.enable();
	removeBtn.enable();
    //被选中得节点
    var selecNode = e.node;
    if(selecNode){
    	httpRequest(selecNode);
    }else{
    	console.log('无树节点上数据');
    }
});
//表格的操作按钮绘制
function onActionRenderer(e) {
	// console.log(e);
    var grid = e.sender;
    var record = e.record;
    var uid = record._uid;
    var rowIndex = e.rowIndex;

    var s = ' <a class="mini-button Edit_Button" href="javascript:onSqlDesign(\'' + uid + '\')" >数据库设计</a>'
    		+ ' <a class="mini-button Edit_Button" href="javascript:onFormDesign(\'' + uid + '\')" >表单设计</a>'
    		+ ' <a class="mini-button Edit_Button" href="javascript:onActivityDesign(\'' + uid + '\')" >流程设计</a>'
		+ ' <a class="mini-button Edit_Button" href="javascript:onDesignerPrint(\'' + uid + '\')" >模板设计</a>'
	+' <a class="mini-button Edit_Button" href="javascript:onRefernce(\'' + uid + '\')" >参照设计</a>';
    return s;
}
//当选中行的时候
function onrowclick(e){
	//启用编辑/删除/发布操作按钮
	//editBtn.enable();
	removeBtn.enable();
	//releaseBtn.enable();
	editModelBtn.enable();
	removeModelBtn.enable();
}
//增加模型
function addModel(){
	//得到被点击的树节点
	var treeNode = tree.getSelectedNode();
	if(treeNode){
		mini.open({
            url: url +"creatModelManage/creatModel.html",
            title: "新增模型", width: 580, height: 220,
            onload: function () {
                var iframe = this.getIFrameEl();
                var data = {
                    action: "new",
                    classData: treeNode
                };
                iframe.contentWindow.SetData(data);
            },
            ondestroy: function (action) {
            	if(action == 'save'){
            		//重新渲染模型数据表
            		httpRequest();
            	}
            	//refresh();
            }
        });
	}else{
		mini.alert('请选择分类');
	}
}
//编辑模型
function onEditModel(){
	//得到被选择的模型
	var row = grid.getSelected();
	if(row){
		mini.open({
            url: url +"creatModelManage/creatModel.html",
            title: "编辑模型", width: 600, height: 200,
            onload: function () {
                var iframe = this.getIFrameEl();
                var data = {
                    action: "edit",
                    modelId: row.id
                };
                iframe.contentWindow.SetData(data);
            },
            ondestroy: function (action) {
            	//重新渲染模型数据表
        		httpRequest();
            }
        });
	}else{
		mini.alert('请选择需要编辑的模型');
	}
}
//删除模型
function removeModel(){
	//得到被选择的模型
	var row = grid.getSelected();
	//判断是否选中模型
	if(row){
		mini.confirm('是否删除选中记录','系统提示',function(action){
			if(action == 'ok'){
				var modelId = row.id;
				var idObj = {
						modelId: modelId
				}
				var idString = JSON.stringify(idObj);
				//加密
				// idString = encrypt(idString);
				$.ajax({
					 url: ajaxUrl + "/model/deleteModel.do",
					 //url: "http://192.168.31.65:8080/bpm/model/deleteModel.do",
					 type:"post",
					 data: idString,
					 contentType : "application/utf-8",
					 success: function(data){
						 //data = data.data;
						 //解密
						 //var decryptData = decrypt(data);
						 //var decryptData = JSON.parse(data);
						 if(data.state == 'success'){
							 mini.alert(data.message);
							//重新渲染模型数据表
							  httpRequest(tree.getSelectedNode());
						 }else{
							 console.log('删除失败');
						 }
					 },
					 error: function(data){
						 
					 }
				})
			}
		})
	}else{
		mini.alert('请选择需要删除的模型');
	}
}

//插入节点确定
function updateClassName() {            
    var form = new mini.Form("#editform");
    var o = form.getData();
    var className = o.modelClassName;
    if(className){
    	var node = tree.getSelectedNode();
        var id;
        if(classState){
        	id = '';
        }else{
        	id = node.id;
        }
        //将分类名称和父id传给后台
        classRequest(className,pid,id);
    }else{
    	mini.alert('请填写分类名称');
    }
}
//取消编辑分类
function cancelEditClass(){
	editWindow.hide();
}
//加载树
function treeHttpRequest(){
	//请求树的数据
	$.ajax({
		  url: ajaxUrl + "/modelC	lass/findAll.do",
		  //url: "http://192.168.11.160:8080/bpm/modelClass/findAll.do",
		  type:"post",
		  contentType : "application/json",
		  success: function (data) {
			  var decryptData = data.data;
			  //解密
			  var treeData = decryptData;
			  //pid加载树的方式
			  tree.loadList(treeData, "id", "pid");
			  //tree.setData(treeData);			//children加载树的方式
		  },
		  error:function(data){
		      mini.alert('失败');
		  }
	});  
}
//点击树节点请求表格数据
function httpRequest(selecNode){
	//得到被点击的树节点
	var treeNode;
	if (selecNode) {
		treeNode = selecNode;
	}else {
		treeNode = tree.getSelectedNode();
	}
	var modelClassObj = {
			modelClassId: treeNode.id
	};
	var idString = JSON.stringify(modelClassObj);
	//加密
	//请求树节点对应的表数据
	$.ajax({
		  url: ajaxUrl + "/model/findByModelClassId.do",
		  type:"post",
		  data: idString,
		  contentType : "application/utf-8",
		  success: function (data) {
			  var decryptData = data;
			  //空：无数据
			  if(decryptData.state == 'error'){
				  grid.setData([]);
				  //showTips(treeNode.modelClassName);
				  mini.showTips({
					  content: "<b>" + treeNode.modelClassName + "</b> <br/>暂时无数据",
					  state: "success",
					  x: "center",
					  y: "center",
					  timeout: 2000
				  });
			  }else{
				  var modelList = decryptData.data;
				  modelList.forEach(function(item,index){
					  item.createDate = formatDate(item.createDate);
				  });
				  grid.setData(modelList);
			  }
		      //grid.setData(data.treeDate);
		  },
		  error:function(data){
		      mini.alert('请求失败');
		  }
	});
}
//新增/编辑分类
function classRequest(className,pid,id){
	var classObj = {
		pid: pid,
		id: id,
		modelClassName: className
    };
    var classString = JSON.stringify(classObj);
    //加密
    //classString = encrypt(classString);
	$.ajax({
		  url: ajaxUrl + "/modelClass/insertModelClass.do",
		  //url: "http://192.168.11.160:8080/bpm/modelClass/insertModelClass.do",
		  type:"post",
		  data: classString,
		  contentType : "application/utf-8",
		  success: function (data) {
			  //解密
			  // var decryptData = decrypt(data);
			  // decryptData = JSON.parse(decryptData);
			  if(data.state == 'success'){
				  //编辑分类名称窗口关闭
				  editWindow.hide();
				  //提示保存状态
				  //mini.alert(decryptData.message);
				  showTips2();
				  //刷新树
				  treeHttpRequest();
			  }else{
				  mini.alert('新增分类失败');
			  }
			  //tree.setData(treeData);
		  },
		  error:function(data){
		      mini.alert('失败');
		  }
	});  
}
//校验分类名称重复
function findByModelClassName(){
	var form = new mini.Form("#editform");
    var o = form.getData();
    var className = o.modelClassName;
	$.ajax({
		  url: ajaxUrl + "/modelClass/findByModelClassName.do",
		  //url: "http://192.168.31.65:8080/bpm/modelClass/findByName.do",
		  type:"post",
		  data: {
			  modelClassName: className
		  },
		  success: function (data) {
		  	data=$.parseJSON(data);
			   if(data.state == 'success'){
				  // mini.alert(data.message);
			  }else{
			  		mini.alert("校验失败，分类名不能重复")
			   }
		  },
		  error:function(data){
		      alert('失败');
		  }
	});
}
//校验必输
function onNotSpaceValidation(e) {
    if (e.isValid) {
        if (!e.value) {
            e.errorText = "不能为空";
            e.isValid = false;
        }
    }
}
//跳转到数据库设计器
function onSqlDesign(row_uid){
	var row = grid.getRowByUID(row_uid);
	if(row){
		//跳转到数据库设计器
		localStorage.setItem("sqlData",JSON.stringify(row));
		var item = {
		    iconCls: "fa fa-desktop",
		    // id: formId,
		    text: "数据库设计器",
		    url: "../pages/sqlDesign/sqlDesign.html"
		};
		parent.activeTab(item);//与父页面通信
	}
}
//跳转到表单设计器
function onFormDesign(row_uid) {
	var row = grid.getRowByUID(row_uid);
	var modelId = row.id;
	// localStorage.setItem("formDesignData",JSON.stringify(row));
	localStorage.setItem("modelId",modelId);
	var item = {
		iconCls : "fa fa-desktop",
		text : "表单设计器",
		url : "../pages/formDesign/formDesign4.html"
	}
	parent.activeTab(item);
	//
	//
	// $.ajax({
	// 	url : ajaxUrl + "/formltems/findByModelId.do?modelId=" + row.id,
	// 	type : "post",
	// 	dataType : "json",
	// 	contentType : "application/json",
	// 	success : function (data) {
	// 		console.log(data)
	// 		if (data.state == "success"){
	// 			row.jumpType = "model";
	// 		}else{
	// 		    row.jumpType = "model_edit";
	// 		    row.edit_data = data.formItem;
	// 		    row.formListId = data.formListId;
	// 		    row.formName = data.formName;
	// 		    row.modelId = data.modelId;
	// 		}
	// 		localStorage.setItem("formDesignData",JSON.stringify(row));
	// 		var item = {
	// 			iconCls : "fa fa-desktop",
	// 			text : "表单设计器",
	// 			url : "../pages/formDesign/formDesign4.html"
	// 		}
	// 		parent.activeTab(item);
	// 	},
	// 	error : function (data) {
	//
	// 	}
	// })
}
//跳转到流程管理控制台
function onActivityDesign(row_uid){
	var row = grid.getRowByUID(row_uid);
	//跳转到数据库设计器
	localStorage.setItem("id",JSON.stringify(row.id));
	row=JSON.stringify(row);
	if(row){
		var item = {
			iconCls: "fa fa-desktop",
			// id: formId,
			text: "流程管理控制台",
			url: "../pages/activiti/activiti_model_list.html",
			row:row
		};
		parent.activeTab(item);//与父页面通信
		// window.location.href= encodeURI("../../pages/activiti/activiti_model_list.html?row ="+row);
	}
}
function onRefernce (row_uid) {
	var rowTAB = grid.getRowByUID(row_uid);
	var modelName=mini.clone(rowTAB);
	localStorage.setItem("modelName",JSON.stringify(modelName));
	var modelId = rowTAB.id;
	localStorage.setItem("modelId",modelId);
	if (rowTAB){
		var item = {
			iconCls: "fa fa-desktop",
			// id: formId,
			text: "参照规则列表",
			url: "../pages/reference/RefList.html",
			data:rowTAB
		};
		parent.activeTab(item);//与父页面通信
	}
}

//跳转到模块设计
function onDesignerPrint(row_uid){
	var row = grid.getRowByUID(row_uid);
	if(row){
		//跳转到模块设计
		localStorage.setItem("row",JSON.stringify(row));
		var item = {
			iconCls: "fa fa-desktop",
			// id: formId,
			text: "打印模板设计",
			url: "../pages/DesignerPrint/PrinterCentre.html"
		};
		parent.activeTab(item);//与父页面通信
	}
}

//提示信息
function showTips2() {
    mini.showTips({
        content: "新增成功",
        state: "success",
        x: "center",
        y: "center",
        timeout: 1000
    });
}